package com.go.where.manager.interceptor;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.go.where.manager.common.UserInfoThreadLocal;
import com.go.where.manager.freemarker.CustomFreemarkerMethod;
import com.go.where.manager.service.system.MenuBuildService;
import com.go.where.manager.util.CommonUtil;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class CheckGrantInterceptor extends MethodFilterInterceptor {
	private static final long serialVersionUID = 8109886567899928146L;
	private static final Logger log = Logger
			.getLogger(CheckGrantInterceptor.class);
	@Resource(name = "menuBuildService")
	private MenuBuildService menuBuildService;
	protected String redirectionUrl;

	public String getRedirectionUrl() {
		return redirectionUrl;
	}

	public void setRedirectionUrl(String redirectionUrl) {
		this.redirectionUrl = redirectionUrl;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@Override
	public String doIntercept(ActionInvocation invocation) throws Exception {
		String cUrl = ServletActionContext.getRequest().getServletPath();
		if (StringUtils.trim(cUrl) == null
				|| StringUtils.trim(cUrl).length() == 0)
			cUrl = ServletActionContext.getRequest().getRequestURI().replace(
					ServletActionContext.getRequest().getContextPath(), "");
		String url = CustomFreemarkerMethod.dispose(cUrl);
		boolean f = false;
		if (UserInfoThreadLocal.get() != null) {
			String serviceCode = UserInfoThreadLocal.get().getServiceCode();
			String code = menuBuildService.getCode(url);
			List<String> json = CommonUtil.gson().fromJson(serviceCode,
					new TypeToken<List<String>>() {
					}.getType());
			log.info("code:" + code + "-list:" + json);
			// 不需要权限控制的，直接跳过
			if (code == null || code.trim().length() == 0) {
				f = true;
			} else if (code != null) {
				if (json != null)
					for (String co : json)
						if (co != null && co.equals(code)) {
							f = true;
						}
			}
		}
		if (!f) {
			log.info("nopermission");
			return "nopermission";
		}
		return invocation.invoke();
	}
}
